import jieba
#主函数
def main():
    txt = getText("test.txt")
    words = cutWords(txt)
    result = countWord(words)
    print_f(result)
#获取文本
def getText(path):
    # 编码格式有问题哦，我的电脑是ANSI 有人是utf-8
    txt = open(path, 'r', encoding='ANSI').read()
    return txt
#对获取到的文本进行分词
def cutWords(txt):
    words = jieba.lcut(txt)
    return words
#进行统计
def countWord(words):
    counts = dict()
    for word in words:
        if(len(word)==1):
            continue
        else:
            if(word[-1]=="曰"):
                word = word[0:-1]
            counts[word] = counts.get(word, 0) + 1
    result = list(counts.items())
    result.sort(key=lambda x:x[1], reverse=True)
    return result
#输出
def print_f(result):
    fo = open("output.txt", "w")
    for i in range(5):
        fo.write(str(result[i])+"\n")
    print("输出成功")
main()
